var qcloud = require('../vendor/wafer2-client-sdk/index')
var config = require('../config')
var formatTime = date => {
  
  if(date){
    date = new Date(date)
  }else{
    date=new Date()
  }
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()
  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

var formatDate = date => {
  if (date) {
    date = new Date(date)
  } else {
    date = new Date()
  }
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  return [year, month, day].map(formatNumber).join('-')
}

var formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}


// 显示繁忙提示
var showBusy = text => wx.showToast({
    title: text,
    icon: 'loading',
    duration: 10000
})

// 显示成功提示
var showSuccess = text => wx.showToast({
    title: text,
    icon: 'success'
})

// 显示失败提示
var showModel = (title, content) => {
    wx.hideToast();

    wx.showModal({
        title,
        content: content+'',
        showCancel: false
    })
}
//后台验证登陆错误后重新登陆
var relogin = (in_this,needUserInfo) => {
  console.log('start relogin', needUserInfo);
  var self = in_this
  // 调用登录接口
  return qcloud.login({
    success(result) {
      if (result) {
        if (needUserInfo && (typeof needUserInfo === "function")){
          needUserInfo(result);
        } else {
          showModel('提示', 'login系统繁忙，请稍后再试')
        }
      } else {
        // 如果不是首次登录，不会返回用户信息，请求用户信息接口获取
        qcloud.request({
          url: config.service.requestUrl,
          login: true,
          success(result) {
            if (needUserInfo && (typeof needUserInfo === "function")) {
              needUserInfo(result.data.data);
            } else {
              showModel('提示', 'qcloud系统繁忙，请稍后再试')
            }
          },
          fail(error) {
            showModel('出错', '系统繁忙，请稍后再试')
            console.log('request fail', error)
          }
        })
      }
    },
    fail(error) {
      wx.showModal({
        title: '提示',
        content: '未经授权，该功能不可用，是否前往授权？',
        confirmText: '是',
        cancelText: '否',
        success: function (res) {
          if (res.confirm) {
            wx.openSetting({
              success: function success(res) {
                // wx.navigateBack({
                //   delta: 1
                // })
              }
            });
          } else if (res.cancel) {
            wx.navigateBack({
              delta: 1
            })
          }
        }
      })
    }
  })
}
module.exports = { formatTime, formatDate, showBusy, showSuccess, showModel, relogin }
